<?php
include_once('includes.php'); 	

//------------------------------------------------------------------

//------------------------------------------------------------------

$sql = "select * from matchs  where  status<2  order by status asc ,kick_off asc ";
$matchs=db_fetch_all($sql);
foreach($matchs as $match)
{
	$now = convertTimeToLocal( date("Y-m-d H:i:s") , date("O")/100 );	
	$difference = strtotime(convertTimeToLocal($match->kick_off,$match->timezone)) - strtotime($now); 
	$minremain =  round($difference/60);
	
	if( $minremain >-120 && $minremain <= 60 )
	{
		echo "<hr/><h2>".$match->versus." ( ".$match->url." )</h1>";
		$url=  $match->url;
				
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		$html = curl_exec($ch);

		curl_close($ch);
		//-----------------------
		
		$patterns = array();
		$patterns[0] = '/<tbody>/';
		$patterns[1] = '/<\/tbody>/';
		$patterns[2] = '/<strong>/';
		$patterns[3] = '/<\/strong>/';
		$html = preg_replace($patterns, '', $html);
	
		//----------------------------		

		$dom = new DOMDocument();
		@$dom->loadHTML($html);
		$xpath = new DOMXPath($dom);

		$elements = $xpath->query('//table[@id="customers"]/tr/td/a');
		parseHtml($match->id,$elements);	
			
	
	}
}


//=====================================================================
function parseHtml($match_id,$elements)
{
	
	if (!is_null($elements)) {
		foreach ($elements as $element) 
		{
			
			$channelName = trim($element->nodeValue);
			$channelUrl = trim($element->getAttribute('href'));
			
			if(isSopcastChannel($channelName))
			{
				echo "<div><strong>".$channelName." ( ".$channelUrl." )</strong></div>";
					
				$ch = curl_init($channelUrl);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HEADER, 0);
				$html = curl_exec($ch);

				curl_close($ch);


				$domchannel = new DOMDocument();
				@$domchannel->loadHTML($html);
				$xpathchannel = new DOMXPath($domchannel);

				$elementschannel = $xpathchannel->query('//table[@id="customers"]/tbody/tr/td/a');
				foreach ($elementschannel as $elementchannel) 
				{
					$channelLink = trim($elementchannel->nodeValue);
					if(isSopcastLink($channelLink))
					{
						
						$sql = "select * from channel where match_id=".addslashes($match_id)." and link='".$channelLink."'";
						$channel=db_fetch_one($sql);
						if(!$channel)
						{
							echo "[New]".$channelLink."<br/>";
							
							$data_channel["match_id"] = $match_id;
							$data_channel["name"] = $channelName;
							$data_channel["link"] = $channelLink;
							$data_channel["type"] = "sopcast";
							$channel_id=db_insert("channel",$data_channel);	
						}	
						else echo "<em>[Existed]".$channelLink."</em><br/>";
					}	
					
				}
			}	
			
		}
	}
}
?>